import lib.XML.XMLHelper;
import lib.logging.Logger;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import util.Downloader;

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.xml.parsers.ParserConfigurationException;

public class UpdateAvailable {

	private String url;
	private String updateUrl;

	public UpdateAvailable() {
		url = "http://code.google.com/feeds/p/jbiersubdownloader/downloads/basic";
		updateUrl = "";
	}

	public boolean checkProgram() {
		try {
			return check("JBierSubDownloader", "jar");
		} catch (Exception e) {
			Logger.instance.error(Logger.stack2String(e));
		}
		return false;
	}

	public boolean checkMapping() {
		try {
			return check("Mapping", "xml");
		} catch (Exception e) {
			Logger.instance.error(Logger.stack2String(e));
		}

		return false;
	}

	public String getUpdateUrl() {
		return updateUrl;
	}

	private boolean check(String baseName, String extension)
			throws ParserConfigurationException, SAXException, IOException {
		Document doc = getRSSDocument();
		NodeList nList = doc.getElementsByTagName("entry");
		for (int i = 0; i < nList.getLength(); i++) {
			if (nList.item(i).getNodeType() == Node.ELEMENT_NODE) {
				Element eElement = (Element) nList.item(i);
				String title = XMLHelper.getStringTagValue("title", eElement);
				if (title.contains(baseName) && title.contains(extension)) {
					String updated = XMLHelper.getStringTagValue("updated",
							eElement);
					updated = updated.substring(0, updated.indexOf("T"));

					try {
						DateFormat formatter;
						Date updatedDate;
						Date versionDate;
						formatter = new SimpleDateFormat("yyyy-MM-dd");
						updatedDate = (Date) formatter.parse(updated);
						versionDate = (Date) formatter.parse(Version.UPDATED);
						if (updatedDate.after(versionDate)) {
							updateUrl = XMLHelper.getStringAtributeValue("link", "href", eElement);
							return true;
						}
					} catch (ParseException e) {
						Logger.instance.error(Logger.stack2String(e));
					}	
				}
			}
		}
		return false;
	}

	private Document getRSSDocument() throws ParserConfigurationException,
			SAXException, IOException {
		URLConnection conn = new URL(url).openConnection();
		conn.setReadTimeout(2000);
		return XMLHelper.getDocument(Downloader.getUrlContents(conn));
	}

}
